package com.xinwei.leetcode.链表;

import com.sun.xml.internal.bind.v2.util.CollisionCheckStack;

import java.util.HashSet;
import java.util.List;

// https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
public class _160_相交链表 {
    // 暴力解法  --> 不知道为啥失败
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode node1 = headA;
        ListNode node2 = headB;
        while (node1 != null) {
            while (node2 != null) {
                if (node1 == node2) {
                    return node1;
                }
                node2 = node2.next;
            }
            node1 = node1.next;
        }
        return null;
    }

    // 哈希表
    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        HashSet<ListNode> set = new HashSet<>();
        ListNode node1 = headA;
        while (node1 != null) {
            set.add(node1);
            node1 = node1.next;
        }
        ListNode node2 = headB;
        while (node2 != null){
            if (set.contains(node2)) {
                return node2;
            }
            node2 = node2.next;
        }
        return null;
    }

    // 双指针法
    // 虽然可能两条链表的长度不一样，但是如果两个指针把两条表都跑过一遍，那么一定是同步的。
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }

}
